package com.waa.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.waa.gulimall.auth.Service.AuthServerService;
import com.waa.gulimall.auth.feigin.MemberFeignService;
import com.waa.gulimall.auth.vo.UserLoginVo;
import com.waa.gulimall.auth.vo.UserRegistVo;
import com.waa.gulimall.common.constant.AuthServerConstant;
import com.waa.gulimall.common.exception.RRException;
import com.waa.gulimall.common.utils.R;
import com.waa.gulimall.common.vo.MemberRespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class LoginAndRedController {
    /**
     * 发送验证码
     *
     * @return R
     */
    @Autowired
    private AuthServerService authServerService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/email/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("emailNumber") String emailNumber) {
        try {
            authServerService.sendCode(emailNumber);
            return R.ok();
        } catch (RRException e) {
            return R.error(e.getCode(), e.getMsg());
        } catch (Exception e) {
            return R.error(500, "未知异常");
        }
    }

    /**
     *       会员注册模块
     *    //TODO 重定向携带数据，利用session原理，将数据放在session中。
     *   只要跳到下一个页面session里面的数据就会去掉
     *   //TODO 分布式下的session问题
     * RedirectAttributes  addFlashAttribute 模拟重定向携带数据
     * @param userRegistVo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String register(@Valid UserRegistVo userRegistVo, BindingResult result, RedirectAttributes  redirectAttributes){
        if (result.hasErrors()){
            final Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(filedError -> filedError.getField(), fieldError -> fieldError.getDefaultMessage()));
            redirectAttributes.addFlashAttribute("errors",collect);
            //校验出错，转发到注册页
            return "redirect:http://auth.changgou.com/reg.html";
        }
        //1.校验验证码
        final String email = userRegistVo.getEmail();//获取邮箱号
        //获取输入的验证码
        final String code = userRegistVo.getCode();
        //redis中存的验证码
        final String redisValue = redisTemplate.opsForValue().get(AuthServerConstant.EMAIL_CODE_CACHE_PREFIX +email);
        if (!StringUtils.isEmpty(redisValue)){
            //判断如果不是空的
            if (redisValue.split("_")[0].equals(code)){
              //验证码成功后就删除验证码
               redisTemplate.delete(AuthServerConstant.EMAIL_CODE_CACHE_PREFIX +email);//删除后后面如果有相同的验证码就不会通过
                //真正的注册调用远程服务接口进行注册
                try {
                    final R r = memberFeignService.regist(userRegistVo);
                    if (r.getCode()==0){
                        //注册成功返回到登录页面
                        return "redirect:http://auth.changgou.com/login.html";
                    }else {
                        final Map<String, String> errors = new HashMap<>();
                        errors.put("msg",(String) r.getData(new TypeReference<String>(){}));
                        redirectAttributes.addFlashAttribute("errors",errors);
                        return "redirect:http://auth.changgou.com/reg.html";
                    }
                }catch (Exception e){
                    final Map<String, String> errors = new HashMap<>();
                    errors.put("msg","系统异常后台正在修复");
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.changgou.com/reg.html";
                }


            }else {
                final HashMap<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.changgou.com/reg.html";
            }

        }else {
            final HashMap<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.changgou.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录
        final R login = memberFeignService.login(loginVo);
        if (login.getCode()==0){
            //成功
            final MemberRespVo data = (MemberRespVo) login.getData("data", new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://changgou.com";
        }else {
            //登录失败
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",(String) login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.changgou.com/login.html";
        }

    }

}
